//
//  NSString+Extension.m
//  XZ_WeChat
//
//  Created by 郭现壮 on 16/9/27.
//  Copyright © 2016年 gxz. All rights reserved.
//

#import "NSString+Extension.h"

#define EmojiCodeToSymbol(c) ((((0x808080F0 | (c & 0x3F000) >> 4) | (c & 0xFC0) << 10) | (c & 0x1C0000) << 18) | (c & 0x3F) << 24)

@implementation NSString (Extension)

- (NSString *)emoji
{
    return [NSString emojiWithStringCode:self];
}


+(NSMutableAttributedString *)attributedStringFromString:(NSString *)string withLength:(CGFloat)length withFont:(CGFloat)font withColor:(UIColor *)color{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 11;  //设置行间距
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString: string];
    [attributeString addAttributes: @{NSFontAttributeName:[UIFont systemFontOfSize:font],NSForegroundColorAttributeName: color,NSParagraphStyleAttributeName:paragraphStyle}range: NSMakeRange(0, length)];
    return attributeString;
}

+ (NSString *)emojiWithStringCode:(NSString *)stringCode
{
    char *charCode = (char *)stringCode.UTF8String;
    long intCode = strtol(charCode, NULL, 16);
    return [self emojiWithIntCode:(int)intCode];
}

+ (NSString *)emojiWithIntCode:(int)intCode {
    int symbol = EmojiCodeToSymbol(intCode);
    NSString *string = [[NSString alloc] initWithBytes:&symbol length:sizeof(symbol) encoding:NSUTF8StringEncoding];
    if (string == nil) { // 新版Emoji
        string = [NSString stringWithFormat:@"%C", (unichar)intCode];
    }
    return string;
}

- (CGSize)sizeWithMaxWidth:(CGFloat)width andFont:(UIFont *)font
{
    CGSize maxSize = CGSizeMake(width, MAXFLOAT);
    NSDictionary *dict = @{NSFontAttributeName : font};
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
}

- (NSString *)originName
{
    NSArray *list = [self componentsSeparatedByString:@"_"];
    NSMutableString *orgName = [NSMutableString string];
    NSUInteger count = list.count;
    if (list.count > 1) {
        for (int i = 1; i < count; i ++) {
            [orgName appendString:list[i]];
            if (i < count-1) {
                [orgName appendString:@"_"];
            }
        }
    } else {  // 防越狱的情况下，本地改名字
        orgName = list[0];
    }
    return orgName;
}

+ (NSString *)currentName
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMddHHMMss"];
    NSString *currentDate = [dateFormatter stringFromDate:[NSDate date]];
    return currentDate;
}

- (NSString *)firstStringSeparatedByString:(NSString *)separeted
{
    NSArray *list = [self componentsSeparatedByString:separeted];
    return [list firstObject];
}

/**
 * 计算文字高度，可以处理计算带行间距的
 */
- (CGSize)boundingRectWithSize:(CGSize)size font:(UIFont*)font  lineSpacing:(CGFloat)lineSpacing
{
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:self];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpacing;
    [attributeString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, self.length)];
    [attributeString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, self.length)];
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin;
    CGRect rect = [attributeString boundingRectWithSize:size options:options context:nil];
    
    //    NSLog(@"size:%@", NSStringFromCGSize(rect.size));
    
    //文本的高度减去字体高度小于等于行间距，判断为当前只有1行
    if ((rect.size.height - font.lineHeight) <= paragraphStyle.lineSpacing) {
        if ([self containChinese:self]) {  //如果包含中文
            rect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height-paragraphStyle.lineSpacing);
        }
    }
    
    
    return rect.size;
}

//判断是否包含中文
- (BOOL)containChinese:(NSString *)str {
    for(int i=0; i< [str length];i++){
        int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff){
            return YES;
        }
    }
    return NO;
}
//把文件大小转换 kb mb 等
+(NSString *) convertFileSize:(long long)size {
    long kb = 1024;
    long mb = kb * 1024;
    long gb = mb * 1024;
    
    if (size >= gb) {
        return [NSString stringWithFormat:@"%.1f GB", (float) size / gb];
    } else if (size >= mb) {
        float f = (float) size / mb;
        if (f > 100) {
            return [NSString stringWithFormat:@"%.0f MB", f];
        }else{
            return [NSString stringWithFormat:@"%.1f MB", f];
        }
    } else if (size >= kb) {
        float f = (float) size / kb;
        if (f > 100) {
            return [NSString stringWithFormat:@"%.0f KB", f];
        }else{
            return [NSString stringWithFormat:@"%.1f KB", f];
        }
    } else
        return [NSString stringWithFormat:@"%lld B", size];
}

// 和当前时间进行比较  输出字符串为（刚刚几个小时前 几天前 ）

+(NSString *)inputTimeStr:(NSString *)timeStr

{

    NSDate *nowDate = [NSDate date];

    NSDate *sinceDate = [self becomeDateStr:timeStr];

    int i  = [nowDate timeIntervalSinceDate:sinceDate];

    

    NSString  *str  = @"";

    

    if (i <= 60)

    {//小于60s

        str = @"刚刚";

    }else if(i>60 && i<=3600)

    {//大于60s，小于一小时

        str = [NSString stringWithFormat:@"%d分钟前",i/60];

    }else if (i>3600 && i<60*60*24)

    {//

//        if ([self isYesterdayWithDate:sinceDate])
//
//        {//24小时内可能是昨天
//
//            str = [NSString stringWithFormat:@"昨天"];
//
//        }else
//
//        {//今天

            str = [NSString stringWithFormat:@"%d小时前",i/3600];

//        }

    }else

    {//

//        int k = i/(3600*24);
//
//        if ([self isYesterdayWithDate:sinceDate])
//
//        {//大于24小时也可能是昨天
//
//            str = [NSString stringWithFormat:@"昨天"];
//
//        }else
//
//        {

            //在这里大于1天的我们可以以周几的形式显示

//            if (k>=1)
//
//            {
//
//                if (k < [self getNowDateWeek])
//
//                {//本周
//
//                    str  = [self weekdayStringFromDate:[self becomeDateStr:timeStr]];
//
//                }else
//
//                {//不是本周
//
////                    str  = [NSString stringWithFormat:@"不是本周%@",[self weekdayStringFromDate:[self becomeDateStr:timeStr]]];
//
//                    str  = timeStr;
//
//                }
//
//            }else
//
//            {//

                str = [NSString stringWithFormat:@"%d天前",i/(3600*24)];

//            }

//        }

    }

    return str;

}

//把时间字符串转换成NSDate

+ (NSDate *)becomeDateStr:(NSString *)dateStr

{

    NSDateFormatter *formatter2 = [[NSDateFormatter alloc]init];

    [formatter2 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSDate *date1 = [formatter2 dateFromString:dateStr];

    return date1;

}

//把时间转换成星期

+ (NSString*)weekdayStringFromDate:(NSDate*)inputDate {

    

    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];

    

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    

    //    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];

    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"zh-Hans"];

    

    [calendar setTimeZone: timeZone];

    

    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;

    

    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];

    

    return [weekdays objectAtIndex:theComponents.weekday];

}

//判断是否为昨天

+ (BOOL)isYesterdayWithDate:(NSDate *)newDate

{

    BOOL isYesterday = YES;

    NSTimeInterval secondsPerDay = 24 * 60 * 60;

    //

    NSDate *yearsterDay =  [[NSDate alloc] initWithTimeIntervalSinceNow:-secondsPerDay];

    /** 前天判断

     //    NSDate *qianToday =  [[NSDate alloc] initWithTimeIntervalSinceNow:-2*secondsPerDay];

     //    NSDateComponents* comp3 = [calendar components:unitFlags fromDate:qianToday];

     //    if (comp1.year == comp3.year && comp1.month == comp3.month && comp1.day == comp3.day)

     //    {

     //        dateContent = @"前天";

     //    }

     **/

    NSCalendar* calendar = [NSCalendar currentCalendar];

    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;

    //    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;

    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:newDate];

    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:yearsterDay];

    

    if ( comp1.year == comp2.year && comp1.month == comp2.month && comp1.day == comp2.day)

    {

        isYesterday = YES;

    }else

    {

        isYesterday = NO;

    }

    return isYesterday;

}

//判断今天是本周的第几天

+ (int)getNowDateWeek

{

    NSDate *nowDate = [NSDate date];

    NSString *nowWeekStr = [self weekdayStringFromDate:nowDate];

    int  factWeekDay = 0;

    

    if ([nowWeekStr isEqualToString:@"周日"])

    {

        factWeekDay = 7;

    }else if ([nowWeekStr isEqualToString:@"周一"])

    {

        factWeekDay = 1;

    }else if ([nowWeekStr isEqualToString:@"周二"])

    {

        factWeekDay = 2;

    }else if ([nowWeekStr isEqualToString:@"周三"])

    {

        factWeekDay = 3;

    }else if ([nowWeekStr isEqualToString:@"周四"])

    {

        factWeekDay = 4;

    }else if ([nowWeekStr isEqualToString:@"周五"])

    {

        factWeekDay = 5;

    }else if ([nowWeekStr isEqualToString:@"周六"])

    {

        factWeekDay = 6;

    }

    return  factWeekDay;

}

@end
